package com.wnm.web;

import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wnm.pojo.Cart;
import com.wnm.pojo.User;
import com.wnm.service.CartService;
import com.wnm.service.impl.CartServiceImpl;

@WebServlet("/cart/*")
public class CartServlet extends BaseServlet {
	public void addCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
		int goodsid = Integer.parseInt(request.getParameter("gid"));
		int nums = Integer.parseInt(request.getParameter("num"));
		User user = (User) request.getSession().getAttribute("user");
		int userid = user.getId();
		CartService cartService = new CartServiceImpl();
		cartService.addCart(userid, goodsid, nums);
	}

	public void showCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		int userid = user.getId();
		CartService cartService = new CartServiceImpl();
		List<Cart> carts = cartService.findAllByUserid(userid);
		request.setAttribute("carts", carts);
		request.getRequestDispatcher("/pages/cartView.jsp").forward(request, response);

	}
	public void showCart2(HttpServletRequest request, HttpServletResponse response) throws Exception {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		int userid = user.getId();
		CartService cartService = new CartServiceImpl();
		List<Cart> carts = cartService.findAllByUserid(userid);
		ObjectMapper om = new ObjectMapper();
		om.writeValue(response.getWriter(), carts);
		
	}

	public void delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		int userid = Integer.parseInt(request.getParameter("uid"));
		int goodsid =Integer.parseInt(request.getParameter("gid"));
		CartService cartService = new CartServiceImpl();
		cartService.delete(userid,goodsid);				
		
	}
}

